<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台主页</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <h1>首页</h1>

    <button id="btnLogout">退出登录</button>

    <script>
        // 页面加载完成后，自动发起请求，获取用户姓名
        window.onload = () => {
            axios({
                url: 'http://127.0.0.1/api/username',
                method: 'GET'
            }).then(function (res) {
                if (res.data.status !== 0) {
                    alert('您尚未登录，请登录后再执行此操作！')
                    location.href = './login.html'
                } else {
                    alert('欢迎您：' + res.data.username)
                }
            });
        }

        const btn = document.getElementById('btnLogout')
        btn.onclick = () => {
            axios({
                url: 'http://127.0.0.1/api/logout',
                method: 'POST'
            }).then(function (res) {
                console.log(res)
                if (res.data.status === 0) {
                    // 如果 status 为 0，则表示退出成功，重新跳转到登录页面
                    location.href = './login.html'
                    alert('退出成功')
                }
            });
        }
    </script>
</body>

</html>